package com.petecapra.cashflow.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.petecapra.cashflow.model.FrequencyType;
import com.petecapra.cashflow.model.Schedule;
import com.petecapra.cashflow.model.TransactionType;
import com.petecapra.cashflow.model.dao.ScheduleManager;

@Controller
@RequestMapping("/schedules*")
public class SchedulesController {
	
	@Autowired private ScheduleManager scheduleManager;

	@RequestMapping(value = "/{scheduleId}", method = RequestMethod.GET)
	public String get(@PathVariable("scheduleId") long scheduleId, ModelMap modelMap) {
		
		// find the schedule
		Schedule schedule = scheduleManager.findById(scheduleId);
		
		// and add it to the model
		modelMap.addAttribute("schedule", schedule);
		modelMap.addAttribute("transactionTypes", TransactionType.values());
		modelMap.addAttribute("frequencyTypes", FrequencyType.values());	
		
		return "schedules/update";
	}
	
	@Transactional
	@RequestMapping(value = "", method = RequestMethod.PUT)
	public String update(HttpServletRequest request, Schedule schedule) {
		
		// save the schedule first
		scheduleManager.save(schedule);
		
		// now update recurrences of transaction according to schedule
		schedule.updateRecurrences();
		
		// redirect to account view
		return "redirect:/accounts/" + schedule.getAccount().getId();
		
	}
	
}
